layui.use(['jquery', 'common', 'table', 'form', 'layer'], function() {
	var $ = layui.jquery;
	var common = layui.common;
	var table = layui.table;
	var form = layui.form;
	var layer = layui.layer;

	table.render({
		elem: '#table',
		url: 'tableData',
		page: true,
		toolbar: '#tableToolbar',
		defaultToolbar: [],
		skin: 'line',
		request: {
			pageName: 'current',
			limitName: 'size'
		},
		cols: [[
			{type: 'checkbox'},
			{field: 'parent', title: '父菜单', templet: function(d) {
				return d.parent ? d.parent.name : '';
			}},
			{field: 'type', title: '类型'},
			{field: 'name', title: '名称'},
			{field: 'eName', title: '英文名称'},
			{field: 'url', title: '链接地址'},
			{field: 'sort', title: '排序', sort: true},
			{field: 'roles', title: '可访问角色（没有则不限）'},
			{title: '操作', minWidth: 168, toolbar: '#rowToolbar'}
		]],
		autoSort: false,
		initSort: {
			field: 'sort',
			type: 'asc'
		},
		where: {
			orderByField: 'sort',
			isAsc: true
		}
	});
	table.on('toolbar', function(obj) {
		switch (obj.event) {
		case 'add':
			common.toUrl('form');
			break;
		case 'delete':
			var data = table.checkStatus('table').data;
			if (data.length) {
				layer.confirm('确定要删除吗？', function(index) {
					var ids = [];
					$.each(data, function() {
						ids.push(this.id);
					});
					common.getJSON('delete', {ids: ids}, function(data) {
						layer.msg(data.msg);
						if (data.state == 'ok') {
							// 成功，刷新表格
							table.reload('table', {
								page: {
									curr: 1
								}
							});
						}
					});
					layer.close(index);
				});
			}
			break;
		default:
			break;
		}
	});
	table.on('tool', function(obj) {
		var data = obj.data;

		switch (obj.event) {
		case 'edit':
			common.toUrl('form?id=' + data.id);
			break;
		case 'del':
			layer.confirm('确定要删除吗？', function(index) {
				$.getJSON('delete', {ids: data.id}, function(data) {
					layer.msg(data.msg);
					if (data.state == 'ok') {
						// 成功，刷新表格
						table.reload('table', {
							page: {
								curr: 1
							}
						});
					}
				});
				layer.close(index);
			});
			break;
		default:
			break;
		}
	});
	table.on('sort', function(obj) {
		table.reload('table', {
			initSort: obj,
			where: {
				orderByField: obj.field,
				isAsc: obj.type ? obj.type == 'asc' : null
			}
		})
	});
	form.on('submit(search)', function(data) {
		table.reload('table', {
			where: data.field,
			page: {
				curr: 1
			}
		});
	});
});